package org.csu.mybigpro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.csu.mybigpro.domain.Score;
import org.csu.mybigpro.domain.StudyAnalysis;
import org.csu.mybigpro.persistence.ScoreMapper;
import org.csu.mybigpro.persistence.StudyAnalysisMapper;
import org.csu.mybigpro.service.StudyAnalysisService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StudyAnalysisServiceImpl extends ServiceImpl<StudyAnalysisMapper, StudyAnalysis> implements StudyAnalysisService {

    @Resource
    private ScoreMapper scoreMapper;

    @Override
    public Map<String, Object> analyzeStudyBehavior(Long studentId) {
        // 查询该学生所有学习分析数据
        List<StudyAnalysis> list = baseMapper.selectList(new QueryWrapper<StudyAnalysis>().eq("student_id", studentId));

        double totalStudyTime = 0;
        double totalAccessFrequency = 0;
        double totalParticipationRate = 0;
        int count = list.size();

        if (count == 0) return Map.of("message", "无学习数据");

        for (StudyAnalysis sa : list) {
            totalStudyTime += sa.getStudyTime() == null ? 0 : sa.getStudyTime();
            totalAccessFrequency += sa.getAccessFrequency() == null ? 0 : sa.getAccessFrequency();
            totalParticipationRate += sa.getParticipationRate() == null ? 0 : sa.getParticipationRate();
        }

        Map<String, Object> result = new HashMap<>();
        result.put("avgStudyTime", totalStudyTime / count);
        result.put("avgAccessFrequency", totalAccessFrequency / count);
        result.put("avgParticipationRate", totalParticipationRate / count);

        return result;
    }

    @Override
    public Map<String, Object> evaluateStudyEffect(Long studentId, Long courseId) {
        Map<String, Object> result = new HashMap<>();

        // 取学生该课程成绩
        Score score = scoreMapper.selectOne(new QueryWrapper<Score>()
                .eq("student_id", studentId)
                .eq("course_id", courseId));

        if (score == null) {
            result.put("message", "无成绩数据");
            return result;
        }

        // 取学习行为数据（最近一次）
        StudyAnalysis studyAnalysis = baseMapper.selectOne(new QueryWrapper<StudyAnalysis>()
                .eq("student_id", studentId)
                .eq("course_id", courseId)
                .orderByDesc("id")
                .last("LIMIT 1"));

        result.put("score", score.getTotalScore());
        result.put("grade", score.getGrade());

        if (studyAnalysis != null) {
            result.put("studyTime", studyAnalysis.getStudyTime());
            result.put("accessFrequency", studyAnalysis.getAccessFrequency());
            result.put("participationRate", studyAnalysis.getParticipationRate());
        }

        // 简单评估
        String evaluation;
        if (score.getTotalScore() < 60) {
            evaluation = "成绩较差，建议加强学习和辅导。";
        } else if (score.getTotalScore() < 80) {
            evaluation = "成绩一般，建议保持努力。";
        } else {
            evaluation = "成绩优秀，继续保持。";
        }
        result.put("evaluation", evaluation);

        return result;
    }

    @Override
    public String generatePersonalizedRecommendation(Long studentId, Long courseId) {
        // 简单获取学习行为和成绩
        StudyAnalysis sa = baseMapper.selectOne(new QueryWrapper<StudyAnalysis>()
                .eq("student_id", studentId)
                .eq("course_id", courseId)
                .orderByDesc("id")
                .last("LIMIT 1"));

        Score score = scoreMapper.selectOne(new QueryWrapper<Score>()
                .eq("student_id", studentId)
                .eq("course_id", courseId));

        if (sa == null || score == null) {
            return "数据不足，无法生成推荐。";
        }

        // 简单规则推荐
        if ((sa.getStudyTime() == null || sa.getStudyTime() < 60) && score.getTotalScore() < 60) {
            return "建议增加每日学习时长，参加辅导班。";
        }
        if ((sa.getParticipationRate() == null || sa.getParticipationRate() < 50) && score.getTotalScore() < 70) {
            return "建议多参与课堂互动和练习。";
        }
        return "学习表现良好，请继续保持。";
    }
}
